<?php
/**
 * 微信demo
 * User 1874
 */

namespace app\common\demo;

use app\common\controller\Wechat;
use think\facade\Cache;
use think\facade\Env;

class WeChatDemo{
    /*
     * 微信入口
     */
    public function weChatEntrance(){
        $weChat = new Wechat();
        //重定向网址
        $url = url('WeChatLogin/getWeChatInfo');
        //获取code
        $weChat->getCode($url, 1);
        exit();
    }
    /*
	 * 获取微信用户信息
	 */
    public function getWeChatInfo(){
        //是否接收到code
        if(input('code')){
            $weChat = new Wechat();
            //获取网页凭证access_token
            $result = $weChat->getTemporaryAccessToken(input('code'), 1);
            //临时凭证access_token获取授权后用户资料
            $info = $weChat->getOauthUserinfo($result['access_token'], $result['openid']);
            //以下执行代码
            dump($info);
        }else{
            //再次执行入口
            $this->weChatEntrance();
        }
    }
    /*
     * 获取微信签名, 用于分享朋友圈、朋友
     */
    public function getSignature(){
        //是否有缓存
        if(Cache::has('signature')){
            $signature = Cache::get('signature');
        }else{
            $weChat = new Wechat();
            //获取accessToken
            $accessToken = $weChat->getAccessToken();
            //获取js api_ticket签名凭证
            $signature = $weChat->getJsApiTicket($accessToken);
            //保存7100秒
            Cache::set('signature', $signature, 7100);
        }
        $url = Env::get("app.web_url").$_SERVER["REQUEST_URI"];;
        $str = "jsapi_ticket=".$signature."&noncestr=9hKgyCLgGZOgQmEI&timestamp=1421142450&url=".$url;
        $signatureStr = sha1($str);

        return $signatureStr;
    }
}